package cn.tedu.mall.search.service.impl;

import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.pojo.product.model.Spu;
import cn.tedu.mall.pojo.search.entity.SpuForElastic;
import cn.tedu.mall.product.service.front.IForFrontSpuService;
import cn.tedu.mall.search.repository.SpuElasticSearch;
import cn.tedu.mall.search.service.ISearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SearchServiceImpl implements ISearchService {
    //数据需要调用Product模块获取
    @DubboReference
    private IForFrontSpuService dubboFrontSpuService;
    @Autowired
    private SpuElasticSearch spuElasticSearch;
    //加载数据：分页加载
    @Override
    public void loadSpuByPage() {
        //页码
        int page = 1;
        //每页条数
        int pageSize = 10;
        //总页数
        int pages = 0;
        do{
            JsonPage<Spu> spusByPage = dubboFrontSpuService.getSpuByPage(page, pageSize);
            //将spusByPage.getData()进行遍历，逐个转成SpuForElastic
            List<SpuForElastic> spuForElasticList = new ArrayList<>();
            for (Spu spu : spusByPage.getData()) {
                SpuForElastic spuForElastic = new SpuForElastic();
                BeanUtils.copyProperties(spu,spuForElastic);
                spuForElasticList.add(spuForElastic);
            }
            //执行批量新增方法，将数据加载到ES中
            spuElasticSearch.saveAll(spuForElasticList);
            log.info("成功加载第{}页数据到ES中",page);
            pages = spusByPage.getTotalPages();
            page++;
        }while(page<=pages);
    }

    //搜索方法
    @Override
    public JsonPage<SpuForElastic> search(String keyword, Integer page, Integer pageSize) {
        //执行查询方法
        Page<SpuForElastic> spuForElastics = spuElasticSearch.search(keyword,
                PageRequest.of(page - 1, pageSize));
        JsonPage<SpuForElastic> jsonPage = new JsonPage<>();
        jsonPage.setPageNum(spuForElastics.getNumber()+1);
        jsonPage.setPageSize(spuForElastics.getSize());
        jsonPage.setTotalPages(spuForElastics.getTotalPages());
        jsonPage.setTotalCount(spuForElastics.getTotalElements());
        jsonPage.setData(spuForElastics.getContent());
        return jsonPage;
    }
}
